package io.renren.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.R;
import io.renren.wechat.service.contact.ContactService;
import io.renren.wechat.service.domain.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/wechat/contacts")
public class ContactController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ContactController.class);
    private ContactService contactService;


    /**
     * 获取部门成员详情
     * https://work.weixin.qq.com/api/doc/90001/90143/90337
     */
    @RequestMapping("/list")
    public R list(@RequestParam(name = "corpId") String corpId,
                  @RequestParam(name = "deptId", required = false) Integer departmentId,
                  @RequestParam(name = "isFetchChild", required = false, defaultValue = "true") boolean isFetchChild) {
        final List<UserInfo> list = contactService.getUserListInDepartment(corpId, departmentId, isFetchChild);
        LOGGER.debug("query UserListInDepartment by deptId:[{}] list: {}", departmentId, list);

        if (LOGGER.isDebugEnabled()) {
            final String jsonString = JSONObject.toJSONString(list);
            LOGGER.debug("contact list jsonString:\n{}\n", jsonString);
        }

        return R.ok().put("list", list);
    }

    @RequestMapping("/get")
    public R get(@RequestParam(name = "corpId") String corpId,
                 @RequestParam(name = "userId") String userId) {
        if (StringUtils.isBlank(corpId)) {
            return R.error("corpId is required");
        }
        if (StringUtils.isBlank(userId)) {
            return R.error("userId is required");
        }

        final UserInfo userInfo;
        try {
            userInfo = contactService.get(corpId, userId);

            return R.ok().put("userInfo", userInfo);
        } catch (Exception e) {
            LOGGER.debug("get userId=[{}] info failed", userId, e);
            return R.error("userId=[" + userId + "] not found");
        }
    }

    @Autowired
    public void setContactService(ContactService contactService) {
        this.contactService = contactService;
    }
}
